package com.danjinwulian.device.service.impl;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.danjinwulian.common.constant.CacheConstants;
import com.danjinwulian.common.core.redis.RedisCache;
import com.danjinwulian.common.core.text.Convert;
import com.danjinwulian.common.utils.StringUtils;
import com.danjinwulian.common.utils.http.HttpUtils;
import com.danjinwulian.device.service.IMpWeixinService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 微信 业务层处理
 * 
 * @author ken.h
 */
@Service
public class IMpWeixinServiceImpl implements IMpWeixinService
{
    private static final Logger log = LoggerFactory.getLogger(IMpWeixinServiceImpl.class);

    @Autowired
    private RedisCache redisCache;

    @Override
    public Map<String, String> code2Session(String code, String appid, String secret) {
        Map result = new HashMap();
        String rspStr = HttpUtils.sendGet("https://api.weixin.qq.com/sns/jscode2session?appid=" + appid + "&secret=" + secret + "&js_code=" + code + "&grant_type=authorization_code");
        if (StringUtils.isNotEmpty(rspStr))
        {
            JSONObject obj = JSON.parseObject(rspStr);
            result.put("openid", obj.getString("openid"));
            result.put("unionid", obj.getString("unionid"));
            result.put("sessionKey", obj.getString("sessionKey"));
        }

        return result;
    }

    @Override
    public String getAccessToken(String key, String appid, String secret) {
        //查询缓存微信token
        String accessToken = redisCache.getCacheObject(CacheConstants.IOT_DEVICE_KEY + "wx_access_token_" + key);
        if (StringUtils.isEmpty(accessToken)) {
            try {
                // 双重检查，防止重复调接口获取
                accessToken = redisCache.getCacheObject(CacheConstants.IOT_DEVICE_KEY + "wx_access_token_" + key);
                if (StringUtils.isEmpty(accessToken)) {
                    //当token失效，重新获取token
                    String rspStr = HttpUtils.sendGet("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + secret);
                    if (StringUtils.isNotEmpty(rspStr))
                    {
                        JSONObject obj = JSON.parseObject(rspStr);
                        String access_token = obj.getString("access_token");
                        String expires_in = obj.getString("expires_in");
                        if (StringUtils.isNotEmpty(access_token)) {
                            redisCache.setCacheObject(CacheConstants.IOT_DEVICE_KEY + "wx_access_token_" + key, access_token, Convert.toInt(expires_in), TimeUnit.SECONDS);
                            accessToken = obj.getString("access_token");
                        }
                    }
                }
            } catch (Exception e) {
                log.error("获取微信access_token发生异常", e);
                throw e;
            }
        }

        return accessToken;
    }

    @Override
    public String getUserPhoneNumber(String accessToken, String code) {
        String phoneNumber = "";

        if (StringUtils.isNotEmpty(accessToken) && StringUtils.isNotEmpty(code)) {
            Map<String, Object> map = new HashMap<>();//存放参数
            map.put("code", code);

            //发送post请求并接收响应数据
            String rspStr= HttpUtil.createPost("https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + accessToken).contentType("application/json").body(JSON.toJSONString(map)).execute().body();
            if (StringUtils.isNotEmpty(rspStr))
            {
                JSONObject obj = JSON.parseObject(rspStr);
                phoneNumber = obj.getJSONObject("phone_info").getString("purePhoneNumber");
            }
        }

        return phoneNumber;
    }

    @Override
    public String createQrcode(String accessToken, String sceneStr) {
        String qrcodeUrl = "";

        if (StringUtils.isNotEmpty(accessToken) && StringUtils.isNotEmpty(sceneStr)) {
            Map<String, Object> map = new HashMap<>();//存放参数
            map.put("action_name", "QR_LIMIT_STR_SCENE");

            Map<String, Object> sceneStrMap = new HashMap<>();
            sceneStrMap.put("scene_str", sceneStr);
            Map<String, Object> sceneMap = new HashMap<>();
            sceneMap.put("scene", sceneStrMap);

            map.put("action_info", sceneMap);

            //发送post请求并接收响应数据
            String rspStr= HttpUtil.createPost("https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" + accessToken).contentType("application/json").body(JSON.toJSONString(map)).execute().body();
            if (StringUtils.isNotEmpty(rspStr))
            {
                JSONObject obj = JSON.parseObject(rspStr);
                String ticket = obj.getString("ticket");
                if (StringUtils.isNotEmpty(ticket))
                {
                    qrcodeUrl = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" + ticket;
                }
            }
        }

        return qrcodeUrl;
    }

    @Override
    public boolean pushTemplateMessage(String accessToken, Map msgParams) {
        boolean pushFlag = false;

        if (StringUtils.isNotEmpty(accessToken) && StringUtils.isNotEmpty(msgParams)) {
            String rspStr= HttpUtil.createPost("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + accessToken).contentType("application/json").body(JSON.toJSONString(msgParams)).execute().body();
            System.out.println("rspStr:"+rspStr);
            if (StringUtils.isNotEmpty(rspStr))
            {
                Map<String, Object> resultMap = JSON.parseObject(rspStr, Map.class);
                System.out.println("resultMap:"+JSON.toJSONString(resultMap));
                if (resultMap != null && resultMap.get("code") != null && Integer.valueOf(resultMap.get("code").toString()) == 200) {
                    pushFlag = true;
                }
            }
        }

        return pushFlag;
    }
}
